<template>
  <span>{{ displayValue }}</span>
</template>

<script>
export default {
  name: 'AnimatedNumber',
  props: {
    value: {
      type: Number,
      default: 0
    },
    duration: {
      type: Number,
      default: 2000
    }
  },
  data() {
    return {
      displayValue: 0
    }
  },
  watch: {
    value: {
      handler(newVal) {
        this.animateNumber(newVal)
      },
      immediate: true
    }
  },
  methods: {
    animateNumber(target) {
      const startValue = this.displayValue
      const startTime = Date.now()
      const animate = () => {
        const now = Date.now()
        const progress = Math.min((now - startTime) / this.duration, 1)

        // 使用缓动函数
        const easeOutQuart = 1 - Math.pow(1 - progress, 4)

        this.displayValue = Math.floor(startValue + (target - startValue) * easeOutQuart)

        if (progress < 1) {
          requestAnimationFrame(animate)
        } else {
          this.displayValue = target
        }
      }
      requestAnimationFrame(animate)
    }
  }
}
</script>
